import moment from "moment";
import { MutableRefObject, useEffect, useMemo, useRef, useState } from "react";
import { useLocation } from "react-router-dom";

/**
 * 获取参数
 */
export function useParams() {
  const [kvObj, setKvObj] = useState<Record<string, string>>({});
  const { search } = useLocation();
  useEffect(() => {
    const paramsStr = decodeURIComponent(search).slice(1);
    const kvs = paramsStr.split("&");
    const obj: Record<string, string> = {};
    kvs.forEach((kv) => {
      const keyValueArray = kv.split("=");
      if (keyValueArray.length > 1) {
        // 将第一个等号后的部分合并到数组的第一个元素
        const key = keyValueArray[0];
        const value = keyValueArray.slice(1).join("=");
        obj[key] = value;
      }
    });
    setKvObj(obj);
  }, []);
  return kvObj;
}

/**
 * 是否为稳定版本路由
 */
export function useVpStableRoute() {
  const { pathname } = useLocation();

  /**
   * 是否为稳定版本
   */
  const isStableVersion = useMemo(() => {
    return pathname.includes("/vp/stable");
  }, [pathname]);

  return isStableVersion;
}

type UseStateRefReturn<T = any> = [T, MutableRefObject<T>, (newVal: T) => void];

/**
 * useState & useRef
 */
export function useStateRef<T = any>(init: any): UseStateRefReturn<T> {
  const [value, setValue] = useState<T>(init);
  const ref = useRef<T>(init);
  function updateValue(newVal: T) {
    setValue(newVal);
    ref.current = newVal;
  }
  return [value, ref, updateValue];
}

/**
 * 获取某元素高度
 * @param st css选择器
 * @param init 初始值
 * @returns
 */
export function useElementHight(st: string, init: number) {
  const [height, setHeight] = useState(init);

  useEffect(() => {
    const tableHead = document.querySelector(st);
    if (!tableHead) {
      throw new Error("Invalid css selector!");
    }
    const sizeObserver = new ResizeObserver(function (entries) {
      const {
        contentRect: { height },
      } = entries[0];
      setHeight(height || 0);
    });
    sizeObserver.observe(tableHead!);
    return () => {
      sizeObserver.unobserve(tableHead!);
    };
  }, []);

  return height;
}

export function YML(list: any, format = "YYYYMM") {
  if (!list || list.length != 2) return [];
  return getYMList(list[0], list[1], format);
}

export function getYMList(
  start_time: string,
  end_time: string,
  format = "YYYYMM"
) {
  let dateArray = []; // dateArray 起止日期中间的所有日期列表
  let currentDate = moment(start_time); //起止日期
  let stopDate = moment(end_time); //截止日期
  //开始日期小于等于结束日期,并循环
  while (currentDate <= stopDate) {
    dateArray.push(Number(moment(currentDate).format(format))); //两个月份间的所有月份,
    currentDate = moment(currentDate).add(1, "months"); //根据类型+1
  }
  return dateArray;
}

export function urlEncode(param: any, key?: any, encode?: any) {
  if (param == null) return "";
  var paramStr = "";
  var t = typeof param;
  if (t == "string" || t == "number" || t == "boolean") {
    paramStr +=
      "&" +
      key +
      "=" +
      (encode == null || encode ? encodeURIComponent(param) : param);
  } else {
    for (var i in param) {
      var k =
        key == null
          ? i
          : key + (param instanceof Array ? "[" + i + "]" : "." + i);
      paramStr += urlEncode(param[i], k, encode);
    }
  }
  return paramStr;
}
